package com.otod.sys.file.service.impl;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.otod.base.exception.AppException;
import com.otod.base.service.BaseService;
import com.otod.commons.constants.CommonConstant;
import com.otod.commons.constants.LogConstant;
import com.otod.sys.file.mapper.FileMapper;
import com.otod.sys.file.service.IFileService;
import com.otod.sys.vo.FileVo;

/**
 * 统一附件管理
 * @author jqiu
 */
@Transactional(readOnly=true)
@Service(IFileService.BEAN_ID)
public class FileServiceImpl extends BaseService implements IFileService {
	
	@Autowired
	FileMapper fileMapper;
	
	/**
	 * 通过主键查询附件信息
	 */
	public FileVo getById(String id){
		return fileMapper.getById(id);
	}
	
	/**
	 * 新增附件信息
	 */
	@Transactional
	public void insert(FileVo vo){
		fileMapper.insert(vo);
		super.invokeLogInsert("PM_001005",LogConstant.LOG_ADD, vo.getBusitableKey(),"[{\"nVal\":\""+vo.getFileName()+"\",\"name\":\"文件\"}]");
	}

	/**
	 * 通过ID删除附件信息
	 */
	@Transactional
	public void deleteById(String id){
		fileMapper.deleteById(id);
	}
	
	/**
	 * 通过业务表ID 删除附件信息
	 */
	@Transactional
	public void deleteFileByBusiId(String id){
		fileMapper.deleteById(id);//未正确处理
	}


	/**
	 * 通过业务表ID 查询附件信息
	 * @param busiId
	 * @return
	 */
	public List<FileVo> queryFileByBusiId(String busiId){
		Map<String,Object> param = new HashMap<String, Object>();
		param.put("busitableKey", busiId);
		param.put("isDel", CommonConstant.COMMON_NO);
		return fileMapper.queryForList(param);
	}

	@Override
	public List<FileVo> queryForListByDocIds(Map<String,Object> map) {
		return fileMapper.queryForListByDocIds(map);
	}

	@Override
	@Transactional
	public void update(Map<String, Object> map) {
		String id = (String)map.get("uuid");
		FileVo fileVo = fileMapper.getById(id);
		fileMapper.update(map);
		
		super.invokeLogInsert("PM_001005",LogConstant.LOG_DELETE, fileVo.getBusitableKey(),"[{\"nVal\":\""+fileVo.getFileName()+"\",\"name\":\"文件\"}]");	
	}

	@Override
	public List<FileVo> queryforList(Map<String, Object> map) {
		
		return fileMapper.queryForList(map);
	}

	@Override
	@Transactional
	public void insert(List<FileVo> newFilelist,List<FileVo> fileList) throws AppException {
		for (FileVo newfileVo : newFilelist) {
			for (FileVo fileVo : fileList) {
				if(fileVo.getFileName().equals(newfileVo.getFileName())){
					throw new AppException("文件已存在，无需重复添加！");
				}
			}
			this.insert(newfileVo);
		}
		
	}
	
}
